import _ from 'lodash';

const data = {
  cacheList: [],
  baseUrl: '',
  serviceList: [
    {
      name: '',
      url: '',
      type: 'default',
    },
  ],
  userInfo: {},
};

export default {
  namespaced: true,
  state: data,
  getters: {
    getChat(state) {
      return state.cacheList;
    },
    getData: (rootState) => ({ key, modules }) => {
      return rootState[modules][key];
    },
  },
  mutations: {
    updateData(state, { key, value, rootState, modules }) {
      rootState[modules][key] = value;
    },
    initData(state) {
      for (const i in data) {
        if (Object.prototype.hasOwnProperty.call(data, i)) {
          state[i] = data[i];
        }
      }
    },
    setCache: (state, arr) => {
      state.cacheList = arr;
    },
    addCache: (state, name) => {
      if (!state.cacheList.some((v) => v === name)) {
        state.cacheList = [...state.cacheList, name];
      }
    },
    removeCache: (state, name) => {
      _.remove(state.cacheList, (v) => v === name);
    },
  },
  actions: {
    setData({ commit, rootState }, obj) {
      obj = { ...obj, ...{ rootState } };
      commit('updateData', obj);
    },
    mapData({ dispatch }, arr) {
      arr.forEach((v) => dispatch('setData', v));
    },
  },
};
